const app = getApp()
var api = require('../../../utils/api.js')
var util = require('../../../utils/util.js');
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    total:0,  //总瓶数
    residue:0,  //剩余瓶数
    total:0,  //总瓶数
    residue:0,  //剩余瓶数
    activity_status: 0,  //参与活动状态 0.领取成功 1.已领取  2.已领完  3.活动结束  4.不在活动地区
    hidden:true,  //弹窗
    lastTime: 0,
    dataLoaded:false,  //活动详情是否加载完成
    receiveButton:false, //是否点击过领取按钮
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    qqmapsdk = new QQMapWX({
      key: '25FBZ-XOBW3-CHH3V-YBMKG-IVNWT-FYBRE'
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    util.showLoading("获取定位中...");
    setTimeout(function(){
      that.adjustLocation();
    },300)

    let promise = new Promise((resolve, reject) => {
      this.activityDetails(resolve, reject);
    })

    promise.then( () => {
      util.hiddenLoading();
      this.setData({
        dataLoaded: true
      })
      if (this.data.receiveButton){
        this.shopSearch();
      }
    })


  },
  //活动详情
  activityDetails: function (resolve, reject){
    var that =this;
    api.POST({
      params: {},
      url: app.globalData.base_url + 'GiftsArticles/getInfo',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          let total = res.data.data.result.total;
          let residue = res.data.data.result.residue;
          let is_join = res.data.data.result.is_join;
          let is_end = res.data.data.result.is_end;
          let share_img = res.data.data.result.share_img;
          let city_list = res.data.data.result.city_list;
          that.setData({
            total: total,
            residue: residue,
            is_join: is_join,
            is_end: is_end,
            share_img: share_img,
            city_list: city_list
          })
          resolve();
        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络");

      }
    })
  },
  //领酒
  receiveWine:function(){
    var that = this;
    api.POST({
      params: {},
      url: app.globalData.base_url + 'GiftsArticles/submit',
      success: function (res) {
        util.hiddenLoading();
        if (util.isEmpty(res.data.code)) {
          that.setData({
            activity_status: 0,
            hidden: false
          })
          that.activityDetails();
        }else{

          if (res.data.code == '5802') {   //活动不可用
            that.setData({
              activity_status:3,
              hidden:false
            })
          }

          if (res.data.code == '11711') {   //已领取
            that.setData({
              activity_status: 1,
              hidden: false
            })
          }

        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络");

      }
    })
  },

  onShareAppMessage: function (res) {

    var that = this;
    var url = '/activity/pages/issuance/issuance'
    if (res.from === 'menu') {
      // 来自页面内转发按钮
      return {
        title: '酒掌柜来了，万瓶美酒扫码免费领！（泸州专场）',
        path: url,
        imageUrl: that.data.share_img,
        success: function (res) {
          that.setData({
            share: "",
            share_id: "",
            modifyPriceCol: true
          })
        },
        fail: function (res) {
          // 转发失败
        }
      }
    }
  },
  //定位
  adjustLocation: function () {
    var that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        util.hiddenLoading();
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          show_authorization: false
        })
      },
      fail: function (fail_res) {
        util.hiddenLoading();
        util.showError("定位失败");
        if (fail_res.errMsg == "getLocation:fail auth deny" || fail_res.errMsg == "getLocation:fail:auth denied") {
          that.setData({
            show_authorization: true
          })
        }
      }
    })
  },


  shopSearch: function (e) {
    var that =this;
    if(!this.data.dataLoaded){
      util.showLoading("加载中...");
      that.setData({
        receiveButton:true
      })
      return false
    }
    var curTime = e.timeStamp;
    var lastTime = this.data.lastTime;
    this.setData({
      lastTime: curTime
    })
    if (lastTime > 0) {
      if (curTime - lastTime < 5000) {
        return false;
      }
    }
    
    if (this.data.is_end == 1) {  //是否已结束
      this.setData({
        activity_status: 3,
        hidden: false
      })
      return false
    }

    // this.getDataTime();
    if(this.data.is_join==1){  //已领取
      this.setData({
        activity_status: 1,
        hidden:false
      })
      return false
    }

    if (this.data.residue == 0) {  //是否已领完
      this.setData({
        activity_status: 2,
        hidden: false
      })
      return false
    }

    var latitude = this.data.latitude;
    var longitude = this.data.longitude;
    // 调用接口
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        if (res.status == 0) {
          var city = res.result.address_component.city;  //当前城市
          var city_list =that.data.city_list;
          if (city_list.indexOf(city) > -1) {
            //是否当前城市
            that.receiveWine();
          }else{
            //不在活动地区
            that.setData({
              activity_status:4,
              hidden: false
            })
          }
        }
      }
    });

  },
  closeMode:function(){
    this.setData({
      hidden: true,
      lastTime:0
    })
  },
  linkWine:function(e){ //前往酒柜
    var curTime = e.timeStamp;
    var lastTime = this.data.lastTime;
    this.setData({
      lastTime: curTime
    })
    if (lastTime > 0) {
      if (curTime - lastTime < 500) {
        return false;
      }
    }

    wx.switchTab({
      url: '/pages/wineNew/wineNew'
    })


  }
})